<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
  <meta name="format-detection" content="telephone=no, email=no"/>
  <title>正在跳转中</title>
  <script src="./javascript/jquery-3.2.1.min.js" type="text/javascript"></script>

</head>
<body>
<h3 id="tip">UAT页面跳转当中，请稍候...</h3>
<h5 id="storageEnable"></h5>
<h5 id="getQueryString"></h5>
<h4 id="tipMsg"></h4>
<div>
  <label>VIN：</label>
  <div id="vinList" style="width:80%;"></div>
</div>
<div>
  <a href="javascript:void(0)" id="gotomain">进入首页</a>
</div>
</body>
<script>
  $(function () {

    function getQueryString(names, urls) {
      urls = urls || window.location.href;
      urls && urls.indexOf("?") > -1 ? urls = urls.substring(urls.indexOf("?") + 1) : "";
      var reg = new RegExp("(^|&)" + names + "=([^&]*)(&|$)", "i");
      var r = urls ? urls.match(reg) : window.location.search.substr(1).match(reg);
      if (r !== null && r[2] !== "") return unescape(r[2]);
      return null;
    }

    function isWeiXin() {
      var ua = window.navigator.userAgent.toLowerCase();
      if (ua.match(/MicroMessenger/i) == 'micromessenger') {
        return true;
      } else {
        return false;
      }
    }

    var env = getQueryString("env") || "";

    var context = "/ws-api";
    if (env === "dev" || env === "uat") {
      context = context + "-" + env;
    } else {
      context = context + "-uat";
    }

    var code = getQueryString("code") || "";
    //获取当前用户的openId,如果是在微信客户端下，调用接口获取openId
    var openId = window.localStorage.getItem("openId") || getQueryString("openId");
    var openId = openId == 'null' || !openId ? '' : openId;
    if (openId != "") {
      $("#tipMsg").html("获取到OPENID:" + openId);
      login(openId);
      return;
    }

    if (code != "" && openId == "") {
      $("#tipMsg").html("获取openId中");
      //页面跳转后直接调用接口获取openId;
      $.ajax(context + "/api/public/wx/getOpenId", {
        type: "POST",
        data: JSON.stringify({code: code, configType: "公众号"}),
        dataType: "json",
        processDataBoolean: false,
        contentType: "application/json;charset=UTF-8",
        success: function (data) {
          var openId = data.body.openId;
          $("#tipMsg").html("获取到OPENID:" + openId);
          if (openId) {
            login(openId);
          }
        },
        error: function (error) {
          if (error.status == 500) {
            console.log(error.responseJSON.message);
          } else {
            console.log("验证用户绑定VIN码信息失败！")
          }
        }
      });
    } else {
      if (isWeiXin() && openId == "") {
        var redirect_url = encodeURI(window.location.href);
        var url = [];
        url.push("https://open.weixin.qq.com/connect/oauth2/authorize?");
        url.push("appId=wx2d4ff8b7fac19195");
        url.push("&redirect_uri=" + redirect_url);
        url.push("&response_type=code");
        url.push("&scope=snsapi_base");
        url.push("&state=1");
        url.push("&#wechat_redirect");
        var urls = url.join("");
        window.location.href = urls;//获取code
      } else if (isWeiXin()) {
        //clear localStorage
        window.localStorage.removeItem("openId");
        window.location.href = window.location.href;
      } else {
        alert("请刷新重试！");
      }
    }

    $("#gotomain").click(function () {
      openMain();
    })

    function openMain() {
      var pathName = window.location.pathname;
      var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
      if (projectName === "/") {
        projectName = "";
      }
      $("#tipMsg").html("认证数据处理完成，即将跳转");
      window.location.href = window.location.origin + projectName + "/index.html#/home";
      // window.location.href = window.location.origin + projectName + "/index.html#/activity/doubleTwelve";
    }

    function login(openId) {
      window.sessionStorage.setItem("openId", openId);
      $.ajax(context + "/api/public/login", {
        type: "POST",
        data: JSON.stringify({openId: openId}),
        dataType: "json",
        processDataBoolean: false,
        contentType: "application/json;charset=UTF-8",
        success: function (data) {
          if (data.code === "OK") {
            //$("#tipMsg").html("认证数据获取成功");
            try {
              window.sessionStorage.setItem("openId", openId);
              window.sessionStorage.setItem("headImg", data.body.headImg);
              window.sessionStorage.setItem("vin", data.body.vin ? data.body.vin : "");
              window.sessionStorage.setItem("userNum", data.body.userNum ? data.body.userNum : "");
              window.sessionStorage.setItem("mobile", data.body.mobile ? data.body.mobile : "");
              window.sessionStorage.setItem("name", data.body.name ? data.body.name : "");
              window.sessionStorage.setItem("isAuth", data.body.auth);
              if (data.body['vinList']) {
                var vinList = data.body['vinList'].join(",");
                $("#vinList").html(vinList);
                window.sessionStorage.setItem("vinList", vinList);//当前openId下所有的vin
              } else {
                $("#vinList").html(data.body.vin);
              }

            } catch (e) {
              $("#storageEnable").html("storage不可用");
              return;
            }
            $("#openMainAId").css('display', 'block');
            window.setTimeout(() => {
              openMain()
            }, 5000);
          } else {
            $("#tipMsg").html("认证数据获取失败！" + data.message + ",</br>请稍候重试或联系客服");
          }
        },
        error: function (error) {
          /* if (error.status == 500) {
           console.log(error.responseJSON.message);
           } else {
           console.log("验证用户绑定VIN码信息失败！")
           }*/
          var pathName = window.location.pathname;
          var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
          if (projectName === "/") {
            projectName = "";
          }
          //window.location.href = projectName + "/static/index.html?openId=" + openId;
        }
      });
    }
  })
</script>
</html>
